﻿using donet.io.rong;
using donet.io.rong.models;
using EntityFramework.Caching;
using EntityFramework.Extensions;
using Newtonsoft.Json;
using RXY_Mall.Api.Common;
using RXY_Mall.Api.Models;
using RXY_Mall.Core;
using RXY_Mall.Core.Tool;
using RXY_Mall.Data;
using RXY_Mall.Domain;
using RXY_Mall.Services.Base;
using RXY_Mall.Services.Order;
using RXY_Mall.Services.User;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Dynamic;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using WebApi.OutputCache.V2;

namespace RXY_Mall.Api.Controllers
{
    /// <summary>
    /// 用户接口
    /// </summary>
    [RoutePrefix("User")]
    [ApiSecurityFilter]
    public partial class UserController : BaseApiController
    {
        private RXY_MallContext db;
        private UserService userService;
        private OrderService orderService;
        private BaseService baseService;

        /// <summary>
        /// 缓存时间 单位s
        /// </summary>
        public const int CACHETIME = 5;

        public UserController()
        {
            db = new RXY_MallContext();
            userService = new UserService();
            orderService = new OrderService();
            baseService = new BaseService();
        }

        #region 登录/注册
        /// <summary>
        /// 用户注册
        /// </summary>
        /// <param name="input">注册信息</param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        [Route("Register")]
        public async Task<Response<LoginOutput>> Register(RegisterInput input)
        {
            Response<LoginOutput> result = new Response<LoginOutput>();
            result.code = 0;
            result.msg = "";
            result.data = null;
            try
            {
                //推荐人
                if (string.IsNullOrWhiteSpace(input.referrer_name))
                {
                    result.msg = "推荐人不能为空";
                    return result;
                }

                var manager = await db.gw_managers.FirstOrDefaultAsync(u => u.user_name == input.referrer_name && u.role_type == 1);
                if (manager == null)
                {
                    result.msg = "推荐人不存在";
                    return result;
                }

                //检查手机号
                var flag = await db.gw_users.AnyAsync(u => u.name == input.mobile);
                if (flag)
                {
                    result.msg = "手机号已注册";
                    return result;
                }

                //检查验证码
                string error;
                var isCheck = baseService.IsCheckSms(input.mobile, input.code, SMSType.Register, out error);
                if (!isCheck)
                {
                    result.msg = error;
                    return result;
                }

                var user = new gw_user()
                {
                    add_time = DateTime.Now,
                    add_ip = DcRequest.GetIP(),
                    nick_name = input.contacts_name,
                    grade = 0,
                    name = input.mobile,
                    sex = "M",
                    status = 1,
                    token = Guid.NewGuid().ToString(),
                    company_id = manager.company_id,
                };
                db.gw_users.Add(user);

                //密码
                //if (!string.IsNullOrWhiteSpace(input.password))
                //{
                //    var password = EncryptionHelper.EncryptText(input.password);
                //    var gw_user_password = new gw_user_password
                //    {
                //        user_id = user.id,
                //        password = password,
                //        type = 0,
                //        add_time = DateTime.Now,
                //    };
                //    user.gw_user_password.Add(gw_user_password);
                //}

                //资产
                gw_finance_property userProperty = new gw_finance_property()
                {
                    balance = 0,
                    bean = 0,
                    id = user.id,
                    child = 0,
                    exp = 0,
                };
                user.gw_finance_property = userProperty;

                //店铺
                gw_user_store userStore = new gw_user_store()
                {
                    id = user.id,
                    address = input.address,
                    add_time = DateTime.Now,
                    area = input.area,
                    city_code = input.city_code,
                    contacts_name = input.contacts_name,
                    country_code = input.country_code,
                    is_pass = true,
                    manager_id = manager.id,
                    mobile = input.mobile,
                    name = input.store_name,
                    province_code = input.province_code,
                    type = (byte)input.store_type,
                };
                user.gw_user_store = userStore;

                int rows = await db.SaveChangesAsync();

                result = SetToken(user);
                //result.code = 1;
                //result.msg = "注册成功";
                //result.data = true;
            }
            catch (Exception ex)
            {
                result.code = 2;
                result.msg = ex.Message;
                LogHelper.WriteLog(ex);
            }

            return result;
        }

        private async Task FreeRegister(int order_group_id, int user_id, byte help_status = 1)
        {
            using (RXY_MallContext db = new RXY_MallContext())
            {
                var exist = await db.gw_order_group_users.AnyAsync(u => u.order_group_id == order_group_id && u.user_id == user_id);
                if (!exist)
                {
                    //添加助力人
                    var order_group_user = new gw_order_group_user()
                    {
                        order_group_id = order_group_id,
                        add_time = DateTime.Now,
                        is_award = false,
                        is_leader = false,
                        user_id = user_id,
                        help_status = help_status,
                    };
                    //var group_user_free = new gw_order_group_user_free()
                    //{
                    //    user_id = user_id
                    //};
                    //order_group_user.gw_order_group_user_free = group_user_free;
                    db.gw_order_group_users.Add(order_group_user);
                    await db.SaveChangesAsync();
                }
            }
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        [Route("Login")]
        public async Task<Response<LoginOutput>> Login(LoginInput input)
        {
            Response<LoginOutput> result = new Response<LoginOutput>();
            result.code = 0;
            result.msg = "";

            try
            {
                var user = await db.gw_users
                    .Include(u => u.gw_user_store)
                    .FirstOrDefaultAsync(u => u.name == input.name);

                if (user == null || user.deleted == true)
                {
                    result.msg = "该非法访问，你已加入黑名单";
                    return result;
                }

                if (user.status == 0)
                {
                    result.msg = "黑名单用户";
                    return result;
                }

                if (!user.gw_user_store.is_pass)
                {
                    result.msg = "审核中";
                    return result;
                }

                string error = "";
                if (!userService.IsPassword(user.id, input.password, 0, out error))
                {
                    result.msg = error;
                    return result;
                }

                if (user.status == 2)
                {
                    result.msg = "用户被禁用或者被限制";
                    return result;
                }

                //添加用户登录日志
                gw_security_login login_log = new gw_security_login()
                {
                    add_time = DateTime.Now,
                    device_no = input.device_no,
                    ip = DcRequest.GetIP(),
                    type = (int)LoginType.密码登录,
                    user_id = user.id,
                };
                db.gw_security_logins.Add(login_log);

                //融云
                var resRongCloud = RongCloudLogin(user, out error);
                if (!resRongCloud)
                {
                    result.msg = error;
                    return result;
                }

                db.Entry(user).Property(u => u.token).IsModified = true;
                await db.SaveChangesAsync();

                result = SetToken(user);
            }
            catch (Exception ex)
            {
                result.code = 2;
                result.msg = ex.Message;
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        [Route("QuickLogin")]
        public async Task<Response<LoginOutput>> QuickLogin(QuickLoginInput input)
        {
            Response<LoginOutput> result = new Response<LoginOutput>();
            result.code = 0;
            result.msg = "";

            try
            {
                var code = input.code.Trim();

                var user = await db.gw_users
                   .Include(u => u.gw_user_store)
                   .FirstOrDefaultAsync(u => u.name == input.name);

                if (user == null || user.deleted == true)
                {
                    result.msg = "账户名不存在，请重新输入";
                    return result;
                }

                if (user.status == 0)
                {
                    result.msg = "黑名单用户";
                    return result;
                }

                if (!user.gw_user_store.is_pass)
                {
                    result.msg = "审核中";
                    return result;
                }

                //验证码
                string error;
                var isCheck = baseService.IsCheckSms(input.name, input.code, SMSType.QuickLogin, out error);
                if (!isCheck)
                {
                    result.msg = error;
                    return result;
                }

                //添加用户登录日志
                gw_security_login login_log = new gw_security_login()
                {
                    add_time = DateTime.Now,
                    device_no = input.device_no,
                    ip = DcRequest.GetIP(),
                    type = (int)LoginType.快速登录,
                    user_id = user.id,
                };
                db.gw_security_logins.Add(login_log);

                //融云
                var resRongCloud = RongCloudLogin(user, out error);
                if (!resRongCloud)
                {
                    result.msg = error;
                    return result;
                }

                db.Entry(user).Property(u => u.token).IsModified = true;
                await db.SaveChangesAsync();

                result = SetToken(user);
            }
            catch (Exception ex)
            {
                result.code = 2;
                result.msg = ex.Message;
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        /// <summary>
        /// 服务号登录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("ServiceLogin")]
        public async Task<Response<LoginOutput>> ServiceLogin(ServiceLoginInput input)
        {
            Response<LoginOutput> result = new Response<LoginOutput>();
            result.code = 0;
            result.msg = "";

            try
            {
                string url = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx034f1b258856705b&secret=84a8437eda1f7d7ea3418438e7390e75&code={0}&grant_type=authorization_code", input.code);
                using (var client = new HttpClient())
                {
                    // 创建一个异步GET请求，当请求返回时继续处理（Continue-With模式）
                    HttpResponseMessage response = await client.GetAsync(url);
                    string resultStr = await response.Content.ReadAsStringAsync();

                    if (!resultStr.Contains("\"access_token\":"))
                    {
                        LogHelper.WriteLog(resultStr);
                        result.msg = "非法访问";
                        return result;
                    }

                    var oauth = JsonConvert.DeserializeObject<WechatOauth>(resultStr);
                    if (oauth == null)
                    {
                        result.msg = "格式错误";
                        return result;
                    }

                    result = await ThirdLogin(new ThirdLoginInput() { type = BindingType.服务号, access_token = oauth.access_token, open_id = oauth.openid });

                    if (result.code != 1 || result.msg == "未绑定")
                    {
                        result.data = new LoginOutput() { access_token = oauth.access_token, open_id = oauth.openid };
                    }
                    //else
                    //{
                    //    //助力订单
                    //    if (!string.IsNullOrWhiteSpace(input.order_no))
                    //    {
                    //        var order = await db.gw_orders
                    //            .Include(o => o.gw_order_goods)
                    //            .FirstOrDefaultAsync(o => o.order_no == input.order_no);
                    //        if (order != null && order.order_group_id > 0
                    //        && (order.gw_order_goods.goods_type == (int)GoodsType.Welfare || order.gw_order_goods.goods_type == (int)GoodsType.Free))
                    //        {
                    //            await FreeRegister((int)order.order_group_id, result.data.user_id, 3);
                    //        }
                    //    }
                    //}

                    return result;
                }
            }
            catch (Exception ex)
            {
                result.code = 2;
                result.msg = ex.Message;
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        /// <summary>
        /// 第三方登录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        [Route("ThirdLogin")]
        public async Task<Response<LoginOutput>> ThirdLogin(ThirdLoginInput input)
        {
            Response<LoginOutput> result = new Response<LoginOutput>();
            result.code = 0;
            result.msg = "";

            try
            {
                //验证第三方登录
                //验证
                if (input.type == BindingType.WeChat || input.type == BindingType.服务号)
                {
                    string url = string.Format("https://api.weixin.qq.com/sns/auth?access_token={0}&openid={1}", input.access_token, input.open_id);
                    using (var client = new HttpClient())
                    {
                        // 创建一个异步GET请求，当请求返回时继续处理（Continue-With模式）
                        HttpResponseMessage response = await client.GetAsync(url);
                        string resultStr = await response.Content.ReadAsStringAsync();

                        if (!resultStr.Contains("\"errmsg\":\"ok\""))
                        {
                            LogHelper.WriteLog(resultStr);
                            result.msg = "非法访问";
                            return result;
                        }
                    }
                }
                else
                {
                    string url = string.Format("https://graph.qq.com/oauth2.0/me?access_token={0}", input.access_token);
                    using (var client = new HttpClient())
                    {
                        // 创建一个异步GET请求，当请求返回时继续处理（Continue-With模式）
                        HttpResponseMessage response = await client.GetAsync(url);
                        string resultStr = await response.Content.ReadAsStringAsync();

                        if (!resultStr.Contains(input.open_id))
                        {
                            LogHelper.WriteLog(resultStr);
                            result.msg = "非法访问";
                            return result;
                        }
                    }
                }

                //查询第三方登录信息
                var third = db.gw_user_thirds.FirstOrDefault(o => o.open_id == input.open_id && !o.deleted);
                if (third == null)
                {
                    result.code = 1;
                    result.msg = "未绑定";
                    return result;
                }

                third.access_token = input.access_token;
                db.Entry(third).Property(u => u.access_token).IsModified = true;

                var user = await db.gw_users
                   .Include(u => u.gw_user_store)
                   .FirstOrDefaultAsync(u => u.id == third.user_id);

                if (user == null || user.deleted == true)
                {
                    third.deleted = true;
                    third.open_id += "00";
                    third.uid += "00";
                    db.Entry(third).Property(u => u.deleted).IsModified = true;
                    db.Entry(third).Property(u => u.open_id).IsModified = true;
                    db.Entry(third).Property(u => u.uid).IsModified = true;
                    await db.SaveChangesAsync();

                    result.msg = "该非法访问，你已加入黑名单";
                    return result;
                }

                if (user.status == 0)
                {
                    result.msg = "黑名单用户";
                    return result;
                }

                if (!user.gw_user_store.is_pass)
                {
                    result.msg = "审核中";
                    return result;
                }

                if (string.IsNullOrEmpty(user.nick_name))
                {
                    user.nick_name = input.name;
                    db.Entry(user).Property(u => u.nick_name).IsModified = true;
                }
                if (string.IsNullOrEmpty(user.logo))
                {
                    user.logo = input.icon_url;
                    db.Entry(user).Property(u => u.logo).IsModified = true;
                }

                int login_type = (int)LoginType.第三方登录微信;
                if (input.type == BindingType.QQ)
                {
                    login_type = (int)LoginType.第三方登录QQ;
                }

                //添加用户登录日志
                gw_security_login login_log = new gw_security_login()
                {
                    add_time = DateTime.Now,
                    device_no = input.device_no,
                    ip = DcRequest.GetIP(),
                    type = login_type,
                    user_id = user.id,
                };
                db.gw_security_logins.Add(login_log);
                if (input.type != BindingType.服务号)
                {
                    //融云
                    string error;
                    var resRongCloud = RongCloudLogin(user, out error);
                    if (!resRongCloud)
                    {
                        result.msg = error;
                        return result;
                    }
                    db.Entry(user).Property(u => u.token).IsModified = true;
                }
                await db.SaveChangesAsync();

                result = SetToken(user);

            }
            catch (Exception ex)
            {
                result.code = 2;
                result.msg = ex.Message;
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        /// <summary>
        /// 绑定登录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        [Route("BindingLogin")]
        public async Task<Response<LoginOutput>> BindingLogin(BindingLoginInput input)
        {
            Response<LoginOutput> result = new Response<LoginOutput>();
            result.code = 0;
            result.msg = "";

            try
            {
                var third = await ThirdLogin(input.third_login);
                if (third.code != 1 || third.data != null)
                {
                    result.msg = third.msg;
                    return result;
                }

                var user = await db.gw_users
                  .Include(u => u.gw_user_store)
                  .FirstOrDefaultAsync(u => u.name == input.name);

                if (user == null || user.deleted == true)
                {
                    result.msg = "该非法访问，你已加入黑名单";
                    return result;
                }

                if (user.status == 0)
                {
                    result.msg = "黑名单用户";
                    return result;
                }

                if (!user.gw_user_store.is_pass)
                {
                    result.msg = "审核中";
                    return result;
                }

                //判断用户是否绑定
                bool isBanding = await db.gw_user_thirds.AnyAsync(t => t.type == (byte)input.third_login.type && t.user_id == user.id);
                if (isBanding)
                {
                    result.msg = "你已绑定过其他账户";
                    return result;
                }
                string error = "";
                bool flag = baseService.IsCheckSms(input.name, input.code, SMSType.Binding, out error);
                if (!flag)
                {
                    result.msg = error;
                    return result;
                }

                int login_type = (int)LoginType.第三方登录微信;
                if (input.third_login.type == BindingType.QQ)
                {
                    login_type = (int)LoginType.第三方登录QQ;
                }
                else if (input.third_login.type == BindingType.服务号)
                {
                    login_type = (int)LoginType.服务号;
                }

                //添加用户登录日志
                gw_security_login login_log = new gw_security_login()
                {
                    add_time = DateTime.Now,
                    device_no = input.device_no,
                    ip = DcRequest.GetIP(),
                    type = login_type,
                    user_id = user.id,
                };
                db.gw_security_logins.Add(login_log);

                //绑定
                var oauth = new gw_user_third()
                {
                    access_token = input.third_login.access_token,
                    add_time = DateTime.Now,
                    deleted = false,
                    gender = input.third_login.gender,
                    icon_url = input.third_login.icon_url,
                    name = input.third_login.name,
                    oauth_consumer_key = input.third_login.oauth_consumer_key,
                    open_id = input.third_login.open_id,
                    status = 1,
                    type = (byte)input.third_login.type,
                    uid = input.third_login.uid,
                    union_id = input.third_login.union_id,
                    user_id = user.id,
                    usid = input.third_login.usid,
                };

                db.gw_user_thirds.Add(oauth);

                if (input.third_login.type != BindingType.服务号)
                {
                    //融云
                    var resRongCloud = RongCloudLogin(user, out error);
                    if (!resRongCloud)
                    {
                        result.msg = error;
                        return result;
                    }
                    db.Entry(user).Property(u => u.token).IsModified = true;
                }
                var rows = await db.SaveChangesAsync();

                result = SetToken(user);
            }
            catch (Exception ex)
            {
                result.code = 2;
                result.msg = ex.Message;
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        /// <summary>
        /// 融云登录
        /// </summary>
        /// <param name="user"></param>
        /// <param name="error"></param>
        /// <returns></returns>
        private bool RongCloudLogin(gw_user user, out string error)
        {
            error = "";

            if (string.IsNullOrWhiteSpace(AppConfig.RongCloudAppKey))
            {
                user.token = Guid.NewGuid().ToString();
                return true;
            }

            var name = user.nick_name;
            if (string.IsNullOrWhiteSpace(name))
            {
                name = StringHelper.HideMobile(user.name);
            }
            RongCloud rongcloud = RongCloud.getInstance(AppConfig.RongCloudAppKey, AppConfig.RongCloudAppSecret);
            TokenReslut res = rongcloud.user.getToken("u" + user.id.ToString(), name, user.logo == null ? "" : user.logo);

            if (res.getCode() != 200)
            {
                LogHelper.WriteLog(res.getErrorMessage());
                error = res.getErrorMessage();

                return false;
            }
            else
            {
                user.token = res.getToken();

                return true;
            }
        }

        /// <summary>
        /// 绑定登录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("BindingDevice")]
        public async Task<Response<bool>> BindingDevice(BindingDeviceInput input)
        {
            Response<bool> result = new Response<bool>();
            result.code = 0;
            result.msg = "";

            try
            {
                //设备号
                var is_device = await db.gw_security_devices.AnyAsync(d => d.device_no == input.device_no);

                var group_user = await db.gw_order_group_users
                        .FirstOrDefaultAsync(u => u.user_id == input.user_id && u.help_status == 1);
                //不存在
                if (!is_device)
                {
                    var device = new gw_security_device()
                    {
                        user_id = input.user_id,
                        add_time = DateTime.Now,
                        device_no = input.device_no,
                    };

                    db.gw_security_devices.Add(device);
                    if (group_user != null)
                    {
                        device.remark = string.Format("助力成功，order_group_id:{0}", group_user.order_group_id);

                        group_user.help_status = 2;
                        db.Entry(group_user).Property(u => u.help_status).IsModified = true;
                        group_user.complete_time = DateTime.Now;
                        db.Entry(group_user).Property(u => u.complete_time).IsModified = true;
                    }
                }
                else
                {
                    var device = new gw_security_device()
                    {
                        user_id = input.user_id,
                        add_time = DateTime.Now,
                        device_no = input.device_no,
                    };

                    db.gw_security_devices.Add(device);
                    if (group_user != null)
                    {
                        device.remark = string.Format("助力失败，原因：该设备已下载过任销遥云商，order_group_id:{0}", group_user.order_group_id);
                        db.Entry(device).Property(u => u.remark).IsModified = true;

                        group_user.help_status = 5;
                        db.Entry(group_user).Property(u => u.help_status).IsModified = true;
                        group_user.complete_time = DateTime.Now;
                        db.Entry(group_user).Property(u => u.complete_time).IsModified = true;
                    }
                }
                await db.SaveChangesAsync();
                if (group_user != null)
                {
                    orderService.FreeOrder(group_user.order_group_id);
                }

                result.data = true;
                result.code = 1;
            }
            catch (Exception ex)
            {
                result.code = 2;
                result.msg = ex.Message;
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        /// <summary>
        /// 用户退出
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("Exit")]
        public async Task<Response<bool>> Exit(BaseInput input)
        {
            Response<bool> result = new Response<bool>();
            result.code = 0;
            result.msg = "";
            result.data = false;

            try
            {
                var user = await db.gw_users.FirstOrDefaultAsync(u => u.id == input.user_id);

                if (user == null)
                {
                    result.msg = "非法访问，你已加入黑名单，IP：" + DcRequest.GetIP(); ;
                    return result;
                }

                user.token = "";
                db.Entry(user).Property(u => u.token).IsModified = true;
                await db.SaveChangesAsync();

                SignExtension.RemoveToken(user.id);
                result.code = 1;
                result.data = true;
            }
            catch (Exception ex)
            {
                result.code = 2;
                result.msg = ex.Message;
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        /// <summary>
        /// 设置Token
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        private Response<LoginOutput> SetToken(gw_user user)
        {
            Response<LoginOutput> result = new Response<LoginOutput>();
            LoginOutput output = new LoginOutput()
            {
                user_id = user.id,
                name = user.name,
                token = user.token,
            };

            SignExtension.SetToken(user.id, user.token, user.company_id);
            result.code = 1;
            result.data = output;
            //SessionHelper.Add("qujia", user.id.ToString());
            return result;
        }

        #endregion

        #region 个人中心

        /// <summary>
        /// 获取个人信息
        /// </summary>
        /// <param name="user_id">用户ID</param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetUserInfo")]
        public async Task<Response<GetUserInfoOutput>> GetUserInfo(int user_id)
        {
            Response<GetUserInfoOutput> result = new Response<GetUserInfoOutput>();
            result.code = 0;

            try
            {
                var user = await db.gw_users
                    .Include(u => u.gw_finance_property)
                    .Include(u => u.gw_user_store)
                    .Include(u => u.gw_company)
                    //.Include(u => u.gw_user_certification)
                    //.Include(u => u.gw_user_coupon)
                    //.Include(u => u.children)
                    //.Include(u => u.gw_user_third)
                    .Select(u => new GetUserInfoOutput()
                    {
                        status = u.status,
                        user_id = u.id,
                        name = u.name,
                        nick_name = u.nick_name,
                        real_name = u.real_name,
                        address = u.address,
                        logo = u.logo,
                        sex = u.sex,
                        grade = (UserGrade)u.grade,
                        signature = u.signature,
                        _birthday = u.birthday,
                        start_time = u.start_time,
                        end_time = u.end_time,
                        coupon = "0",
                        gw_finance_property = u.gw_finance_property,
                        user_store = u.gw_user_store,
                        gw_company = u.gw_company,
                        //gw_user_certification = u.gw_user_certification,
                        //is_certification = u.gw_user_certification.OrderByDescending(c => c.id).Any(c => c.status == 1),
                        //thirds = u.gw_user_third.Select(o => new user_third { name = o.name, type = o.type }).ToList(),
                        //coupon_count = u.gw_user_coupon.Count(c => c.status == (byte)CouponsStatus.Unused && c.gw_marketing_coupon.deleted == false && c.gw_marketing_coupon.status == 1),
                        //child = u.children.Count,
                        //child_count = u.children.Count,

                    }).FirstOrDefaultAsync(u => u.user_id == user_id);

                if (user == null)
                {
                    result.msg = "非法访问，你已加入黑名单，IP：" + DcRequest.GetIP(); ;
                    return result;
                }
                if (user.status == 2)
                {
                    result.msg = "用户加入黑名单";
                    return result;
                }
                user.name = StringHelper.HideMobile(user.name);
                user.birthday = user._birthday == null ? "" : ((DateTime)user._birthday).ToString("yyyy-MM-dd");
                user.balance = user.gw_finance_property.balance.ToString("0.##");
                user.bean = user.gw_finance_property.bean.ToString("0.##");
                user.exp = user.gw_finance_property.exp.ToString("0.##");
                user.member_start_time = TimeHelper.GetTimeStamp(user.start_time);
                user.member_end_time = TimeHelper.GetTimeStamp(user.end_time);

                if (user.thirds != null && user.thirds.Count > 0)
                {
                    var wechat = user.thirds.FirstOrDefault(o => o.type == (byte)BindingType.WeChat);
                    if (wechat != null)
                    {
                        user.is_wechat = true;
                        user.wechat = wechat.name;

                    }
                    var qq = user.thirds.FirstOrDefault(o => o.type == (byte)BindingType.QQ);
                    if (qq != null)
                    {
                        user.is_qq = true;
                        user.qq = qq.name;
                    }
                }

                if (user.user_store != null)
                {
                    user.store = new StoreOutput()
                    {
                        address = user.user_store.address,
                        area = user.user_store.area,
                        contacts_name = user.user_store.contacts_name,
                        mobile = user.user_store.mobile,
                        store_name = user.user_store.name,
                        store_type = (StoreType)user.user_store.type,
                        telphone = user.user_store.telphone,
                    };
                }
                if (user.gw_company != null)
                {
                    user.contacts_phone = user.gw_company.contacts_phone;
                }
                else
                {
                    user.contacts_phone = "18134711256";
                }
                result.code = 1;
                result.data = user;
                return result;
            }
            catch (Exception ex)
            {
                result.code = 2;
                result.msg = ex.Message;
                LogHelper.WriteLog(ex);
            }

            LogHelper.WriteLog(result.msg);
            return result;
        }

        /// <summary>
        /// 修改用户头像
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("UpdateUserLogo")]
        public async Task<Response<bool>> UpdateUserLogo(UpdateUserLogoInput input)
        {
            Response<bool> result = new Response<bool>();
            result.code = 0;
            result.msg = "";
            result.data = false;

            try
            {

                var date = DateTime.Now.AddMinutes(-20);
                var file = await db.gw_base_files.FirstOrDefaultAsync(f => f.user_id == input.user_id && f.add_time > date && f.url == input.logo);
                if (file == null)
                {
                    result.msg = "请先上传图片";
                    return result;
                }
                file.temp = false;
                db.Entry(file).Property(f => f.temp).IsModified = true;
                await db.SaveChangesAsync();

                var user = await db.gw_users.FindAsync(input.user_id);
                if (user == null)
                {
                    result.code = 0;
                    result.msg = "非法访问，你已加入黑名单，IP：" + DcRequest.GetIP(); ;
                    return result;
                }

                user.logo = input.logo;
                db.Entry(user).Property(u => u.logo).IsModified = true;
                await db.SaveChangesAsync();


                result.code = 1;
                result.data = true;
            }
            catch (Exception ex)
            {
                result.code = 2;
                result.msg = ex.Message;
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        /// <summary>
        /// 修改昵称
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("UpdateNickName")]
        public async Task<Response<bool>> UpdateNickName(UpdateNickNameInput input)
        {
            Response<bool> result = new Response<bool>();
            result.code = 0;
            result.msg = "";
            result.data = false;

            try
            {
                var user = await db.gw_users.FindAsync(input.user_id);
                if (user == null)
                {
                    result.code = 0;
                    result.msg = "非法访问，你已加入黑名单，IP：" + DcRequest.GetIP(); ;
                    return result;
                }

                user.nick_name = input.nick_name;
                db.Entry(user).Property(u => u.nick_name).IsModified = true;
                await db.SaveChangesAsync();


                result.code = 1;
                result.data = true;
            }
            catch (Exception ex)
            {
                result.code = 2;
                result.msg = ex.Message;
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        /// <summary>
        /// 修改性别
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("UpdateSex")]
        public async Task<Response<bool>> UpdateSex(UpdateSexInput input)
        {
            Response<bool> result = new Response<bool>();
            result.code = 0;
            result.msg = "";
            result.data = false;

            try
            {
                var user = await db.gw_users.FindAsync(input.user_id);
                if (user == null)
                {
                    result.code = 0;
                    result.msg = "非法访问，你已加入黑名单，IP：" + DcRequest.GetIP(); ;
                    return result;
                }

                user.sex = input.sex;
                db.Entry(user).Property(u => u.sex).IsModified = true;
                await db.SaveChangesAsync();

                result.code = 1;
                result.data = true;
            }
            catch (Exception ex)
            {
                result.code = 2;
                result.msg = ex.Message;
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        /// <summary>
        /// 修改签名
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("UpdateSignature")]
        public async Task<Response<bool>> UpdateSignature(UpdateSignatureInput input)
        {
            Response<bool> result = new Response<bool>();
            result.code = 0;
            result.msg = "";
            result.data = false;

            try
            {
                var user = await db.gw_users.FindAsync(input.user_id);
                if (user == null)
                {
                    result.code = 0;
                    result.msg = "非法访问，你已加入黑名单，IP：" + DcRequest.GetIP(); ;
                    return result;
                }

                user.signature = input.signature;
                db.Entry(user).Property(u => u.signature).IsModified = true;
                await db.SaveChangesAsync();


                result.code = 1;
                result.data = true;
            }
            catch (Exception ex)
            {
                result.code = 2;
                result.msg = ex.Message;
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        /// <summary>
        /// 修改出生日期
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("UpdateBirthday")]
        public async Task<Response<bool>> UpdateBirthday(UpdateBirthdayInput input)
        {
            Response<bool> result = new Response<bool>();
            result.code = 0;
            result.msg = "";
            result.data = false;

            try
            {
                var user = await db.gw_users.FindAsync(input.user_id);
                if (user == null)
                {
                    result.code = 0;
                    result.msg = "非法访问，你已加入黑名单，IP：" + DcRequest.GetIP(); ;
                    return result;
                }

                user.birthday = input.birthday;
                db.Entry(user).Property(u => u.birthday).IsModified = true;
                await db.SaveChangesAsync();


                result.code = 1;
                result.data = true;
            }
            catch (Exception ex)
            {
                result.code = 2;
                result.msg = ex.Message;
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        /// <summary>
        /// 修改常住地址
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("UpdateUserAddress")]
        public async Task<Response<bool>> UpdateUserAddress(UpdateUserAddressInput input)
        {
            Response<bool> result = new Response<bool>();
            result.code = 0;
            result.msg = "";
            result.data = false;

            try
            {
                var user = await db.gw_users.FindAsync(input.user_id);
                if (user == null)
                {
                    result.code = 0;
                    result.msg = "非法访问，你已加入黑名单，IP：" + DcRequest.GetIP(); ;
                    return result;
                }

                user.address = input.address;
                db.Entry(user).Property(u => u.address).IsModified = true;
                await db.SaveChangesAsync();


                result.code = 1;
                result.data = true;
            }
            catch (Exception ex)
            {
                result.code = 2;
                result.msg = ex.Message;
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        #endregion

        #region 收货地址
        /// <summary>
        /// 新增地址
        /// </summary>
        /// <param name="input">地址信息输入信息</param>
        /// <returns>data:地址ID</returns>
        [HttpPost]
        [Route("AddAddress")]
        public async Task<Response<string>> AddAddress(AddressInfoInput input)
        {
            Response<string> result = new Response<string>();
            result.code = 0;
            result.msg = "";
            try
            {
                if (!Validator.IsMobile(input.mobile))
                {
                    result.msg = "手机格式不正确";
                    return result;
                }
                var user = await userService.IsUseByUser(input.user_id);
                if (!user.data)
                {
                    result.msg = user.msg;
                    return result;
                }

                if (string.IsNullOrEmpty(input.province_code) || string.IsNullOrEmpty(input.city_code) || string.IsNullOrEmpty(input.country_code))
                {
                    result.msg = "当前本版过低，请升级。";
                    return result;
                }

                gw_user_address_book addressbook = new gw_user_address_book()
                {
                    accepter_name = input.accepter_name,
                    address = input.address,
                    add_time = DateTime.Now,
                    area = input.area,
                    city_code = input.city_code,
                    country_code = input.country_code,
                    is_default = input.is_default,
                    telphone = "",
                    post_code = input.post_code,
                    province_code = input.province_code,
                    user_id = input.user_id,
                    email = "",
                    mobile = input.mobile,
                };

                db.gw_user_address_books.Add(addressbook);
                int row = await db.SaveChangesAsync();
                if (row > 0)
                {
                    if (addressbook.is_default == true)
                    {
                        AddressInput add = new AddressInput()
                        {
                            address_id = addressbook.id,
                            user_id = input.user_id
                        };
                        await SetDefaultAddress(add);
                    }

                    result.code = 1;
                    result.msg = "保存成功";
                }
                else
                {
                    result.code = 0;
                    result.msg = "保存失败";
                }
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                result.code = 2;
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        /// <summary>
        /// 修改地址
        /// </summary>
        /// <param name="input">地址信息输入信息</param>
        /// <returns>data:地址ID</returns>
        [HttpPost]
        [Route("UpdateAddress")]
        public async Task<Response<bool>> UpdateAddress(AddressInfoInput input)
        {
            Response<bool> result = new Response<bool>();
            result.code = 0;
            result.msg = "";
            result.data = false;
            try
            {
                var user = await userService.IsUseByUser(input.user_id);
                if (!user.data)
                {
                    result.msg = user.msg;
                    return result;
                }

                gw_user_address_book addressbook = await db.gw_user_address_books.FindAsync(input.address_id);

                if (addressbook == null)
                {
                    result.msg = "地址不存在";
                    return result;
                }

                if (string.IsNullOrEmpty(input.province_code) || string.IsNullOrEmpty(input.city_code) || string.IsNullOrEmpty(input.country_code))
                {
                    result.msg = "当前本版过低，请升级。";
                    return result;
                }

                addressbook.accepter_name = input.accepter_name;
                addressbook.address = input.address;
                addressbook.add_time = DateTime.Now;
                addressbook.area = input.area;
                addressbook.city_code = input.city_code;
                addressbook.country_code = input.country_code;
                addressbook.is_default = input.is_default;
                addressbook.post_code = input.post_code;
                addressbook.province_code = input.province_code;
                addressbook.mobile = input.mobile;
                db.Entry(addressbook).State = EntityState.Modified;
                int row = await db.SaveChangesAsync();
                if (row > 0)
                {
                    if (addressbook.is_default == true)
                    {
                        AddressInput add = new AddressInput()
                        {
                            address_id = addressbook.id,
                            user_id = input.user_id
                        };
                        await SetDefaultAddress(add);
                    }

                    result.code = 1;
                    result.msg = "保存成功";
                    result.data = true;
                }
                else
                {
                    result.code = 0;
                    result.msg = "保存失败";
                }
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                result.code = 2;
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        /// <summary>
        /// 删除地址
        /// </summary>
        /// <param name="input">地址信息输入信息</param>
        /// <returns>data:地址ID</returns>
        [HttpPost]
        [Route("DeleteAddress")]
        public async Task<Response<bool>> DeleteAddress(AddressInput input)
        {
            Response<bool> result = new Response<bool>();
            result.code = 0;
            result.msg = "";
            result.data = false;
            try
            {
                var user = await userService.IsUseByUser(input.user_id);
                if (!user.data)
                {
                    result.msg = user.msg;
                    return result;
                }

                var addressbooks = await db.gw_user_address_books.Where(a => a.user_id == input.user_id).ToListAsync();
                if (addressbooks == null)
                {
                    result.msg = "无数据";
                    return result;
                }
                var addressbook = addressbooks.FirstOrDefault(a => a.id == input.address_id);
                if (addressbook == null)
                {
                    result.msg = "地址不存在";
                    return result;
                }
                addressbooks.Remove(addressbook);
                db.gw_user_address_books.Remove(addressbook);
                if (addressbook.is_default)
                {
                    var address = addressbooks.FirstOrDefault();
                    if (address != null)
                    {
                        address.is_default = true;
                    }
                }


                int row = await db.SaveChangesAsync();
                if (row > 0)
                {
                    result.code = 1;
                    result.msg = "删除成功";
                    result.data = true;
                }
                else
                {
                    result.code = 1;
                    result.msg = "删除失败";
                }
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                result.code = 2;
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        /// <summary>
        /// 获得所有地址
        /// </summary>
        /// <param name="user_id">用户ID</param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetAddressList")]
        public async Task<Response<List<AddressInfoInput>>> GetAddressList(int user_id)
        {
            Response<List<AddressInfoInput>> result = new Response<List<AddressInfoInput>>();
            result.code = 0;
            result.msg = "";
            try
            {
                var user = await userService.IsUseByUser(user_id);
                if (!user.data)
                {
                    result.msg = user.msg;
                    return result;
                }

                var addressbooks = db.gw_user_address_books.Where(a => a.user_id == user_id).ToList();
                if (addressbooks == null)
                {
                    result.msg = "地址不存在";
                    return result;
                }
                List<AddressInfoInput> output = new List<AddressInfoInput>();
                foreach (var addr in addressbooks)
                {
                    output.Add(ConvertAddress(addr));
                }
                result.code = 1;
                result.msg = "获取成功";
                result.data = output;
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                result.code = 2;
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        /// <summary>
        /// 获得地址信息
        /// </summary>
        /// <param name="user_id">用户ID</param>
        /// <param name="addressId">地址ID</param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetAddress")]
        public async Task<Response<AddressInfoInput>> GetAddress(int user_id, int addressId)
        {
            Response<AddressInfoInput> result = new Response<AddressInfoInput>();
            result.code = 0;
            result.msg = "";
            try
            {
                var user = await userService.IsUseByUser(user_id);
                if (!user.data)
                {
                    result.msg = user.msg;
                    return result;
                }

                var addressbook = await db.gw_user_address_books.FindAsync(addressId);
                if (addressbook == null)
                {
                    result.msg = "地址不存在";
                    return result;
                }
                if (addressbook.user_id != user_id)
                {
                    result.msg = "非法访问";
                    return result;
                }
                AddressInfoInput output = ConvertAddress(addressbook);
                result.code = 1;
                result.msg = "获取成功";
                result.data = output;
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                result.code = 2;
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        /// <summary>
        /// 获得默认地址信息
        /// </summary>
        /// <param name="user_id">用户ID</param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetDefaultAddress")]
        public async Task<Response<AddressInfoInput>> GetDefaultAddress(int user_id)
        {
            Response<AddressInfoInput> result = new Response<AddressInfoInput>();
            result.code = 0;
            result.msg = "";
            try
            {
                var user = await userService.IsUseByUser(user_id);
                if (!user.data)
                {
                    result.msg = user.msg;
                    return result;
                }

                var addressbooks = await db.gw_user_address_books.Where(a => a.user_id == user_id).ToListAsync();
                if (addressbooks == null || addressbooks.Count == 0)
                {
                    result.msg = "地址不存在";
                    return result;
                }
                var defualtAddress = addressbooks.FirstOrDefault(a => a.is_default == true);
                if (defualtAddress == null)
                {
                    defualtAddress = addressbooks.FirstOrDefault();
                }
                AddressInfoInput output = ConvertAddress(defualtAddress);
                result.code = 1;
                result.msg = "获取成功";
                result.data = output;
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                result.code = 2;
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        /// <summary>
        /// 设置成默认地址
        /// </summary>
        /// <param name="input">地址信息输入信息</param>
        /// <returns></returns>
        [HttpPost]
        [Route("SetDefaultAddress")]
        public async Task<Response<string>> SetDefaultAddress(AddressInput input)
        {
            Response<string> result = new Response<string>();
            result.code = 0;
            result.msg = "";
            try
            {
                var addressbooks = await db.gw_user_address_books.Where(u => u.user_id == input.user_id).ToListAsync();
                if (addressbooks == null || addressbooks.Count() == 0)
                {
                    result.msg = "地址不存在";
                    return result;
                }
                foreach (var item in addressbooks)
                {
                    item.is_default = false;
                    if (item.id == input.address_id)
                    {
                        item.is_default = true;
                    }
                    db.Entry(item).State = EntityState.Modified;
                }
                int row = await db.SaveChangesAsync();

                if (row > 0)
                {
                    result.code = 1;
                    result.msg = "设置成功";
                }
                else
                {
                    result.code = 1;
                    result.msg = "设置失败";
                }

            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                result.code = 2;
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        /// <summary>
        /// 数据库地址转化成输出地址
        /// </summary>
        /// <param name="addr"></param>
        /// <returns></returns>
        private AddressInfoInput ConvertAddress(gw_user_address_book addr)
        {
            AddressInfoInput addressInfo = new AddressInfoInput()
            {
                address_id = addr.id,
                accepter_name = addr.accepter_name,
                address = addr.address,
                area = addr.area,
                mobile = addr.mobile,
                post_code = addr.post_code,
                user_id = (int)addr.user_id,
                province_code = addr.province_code,
                city_code = addr.city_code,
                country_code = addr.country_code,
                is_default = addr.is_default,
            };

            return addressInfo;
        }

        #endregion

        #region 身份证认证
        /// <summary>
        /// 添加用户认证
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("AddUserCertification")]
        public async Task<Response<string>> AddUserCertification(UserCertificationInput input)
        {
            Response<string> result = new Response<string>();
            result.code = 0;
            result.msg = "";
            try
            {
                gw_user_certification gw_user_certification = await db.gw_user_certifications.FirstOrDefaultAsync(c => c.user_id == input.user_id);

                if (gw_user_certification != null)
                {
                    result.msg = "用户已认证";
                    return result;
                }

                var user = await db.gw_users.FindAsync(input.user_id);
                user.real_name = input.name;
                db.Entry(user).Property(u => u.real_name).IsModified = true;

                //if (user.real_name != input.name)
                //{
                //    result.msg = "身份证姓名须与会员账号登记姓名一致";
                //    return result;
                //}
                //验证是否是Date类型
                DateTime dtEnd;
                if (DateTime.TryParse(input.end_date, out dtEnd))
                {
                    input.end_date = dtEnd.ToShortDateString();
                }
                gw_user_certification certification = new gw_user_certification()
                {
                    address = input.address,
                    add_time = DateTime.Now,
                    birthdate = input.birthdate,
                    end_date = input.end_date,
                    gender = input.gender,
                    id_type = 1,
                    id_no = input.id_no,
                    issuing_authority = input.issuing_authority,
                    name = input.name,
                    nation = input.nation,
                    picture_front_url = input.picture_front_url,
                    picture_opposite_url = input.picture_opposite_url,
                    picture_hand_url = input.picture_hand_url,
                    start_date = input.start_date,
                    status = 1,
                    user_id = input.user_id,
                };

                db.gw_user_certifications.Add(certification);
                int row = await db.SaveChangesAsync();
                if (row > 0)
                {
                    result.code = 1;
                    result.msg = "保存成功";
                }
                else
                {
                    result.code = 0;
                    result.msg = "保存失败";
                }
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                result.code = 2;
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        /// <summary>
        /// 修改用户认证
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("UpdateUserCertification")]
        public async Task<Response<string>> UpdateUserCertification(UserCertificationInput input)
        {
            Response<string> result = new Response<string>();
            result.code = 0;
            result.msg = "";
            try
            {
                gw_user_certification certification = await db.gw_user_certifications.FindAsync(input.certification_id);

                if (certification == null)
                {
                    result.msg = "用户认证不存在";
                    return result;
                }

                var user = await db.gw_users.FindAsync(input.user_id);

                if (user.real_name != input.name)
                {
                    result.msg = "真实姓名不一致";
                    return result;
                }


                user.real_name = input.name;
                db.Entry(user).Property(u => u.real_name).IsModified = true;

                certification.address = input.address;
                certification.add_time = DateTime.Now;
                certification.birthdate = input.birthdate;
                certification.end_date = input.end_date;
                certification.gender = input.gender;
                certification.id_type = 1;
                certification.id_no = input.id_no;
                certification.issuing_authority = input.issuing_authority;
                certification.name = input.name;
                certification.nation = input.nation;
                certification.picture_front_url = input.picture_front_url;
                certification.picture_opposite_url = input.picture_opposite_url;
                certification.picture_hand_url = input.picture_hand_url;
                certification.start_date = input.start_date;
                certification.status = 1;
                certification.user_id = input.user_id;

                db.Entry(certification).State = EntityState.Modified;
                int row = await db.SaveChangesAsync();
                if (row > 0)
                {
                    result.code = 1;
                    result.msg = "修改成功";
                }
                else
                {
                    result.code = 0;
                    result.msg = "修改失败";
                }
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                result.code = 2;
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        /// <summary>
        /// 获得用户认证
        /// </summary>
        /// <param name="user_id">用户ID</param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetUserCertification")]
        public async Task<Response<GetUserCertificationOutput>> GetUserCertification(int user_id)
        {
            Response<GetUserCertificationOutput> result = new Response<GetUserCertificationOutput>();
            result.code = 0;
            result.msg = "";
            try
            {
                result.code = 1;
                var certification = await db.gw_user_certifications
                    .OrderByDescending(c => c.id)
                    .Select(c => new GetUserCertificationOutput()
                    {
                        certification_id = c.id,
                        address = c.address,
                        _birthdate = c.birthdate,
                        end_date = c.end_date,
                        gender = c.gender,
                        id_no = c.id_no,
                        name = c.name,
                        user_id = c.user_id,
                    })
                    .FirstOrDefaultAsync(c => c.user_id == user_id);

                if (certification == null)
                {
                    result.msg = "用户认证不存在";
                    return result;
                }

                certification.birthdate = certification._birthdate.ToString("yyyy-MM-dd HH:mm:ss");
                result.msg = "获取成功";
                result.data = certification;
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                result.code = 2;
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        #endregion

        #region 更换手机号
        /// <summary>
        /// 更换手机号-第一步
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("UpdateMobile")]
        public async Task<Response<bool>> UpdateMobile(UpdateMobileInput input)
        {
            Response<bool> result = new Response<bool>();
            result.code = 0;
            result.msg = "";
            result.data = false;
            try
            {
                var user = await db.gw_users.FindAsync(input.user_id);
                if (user == null)
                {
                    result.msg = "非法访问，你已加入黑名单，IP：" + DcRequest.GetIP(); ;
                    LogHelper.WriteLog(result.msg);
                    return result;
                }

                string error = "";
                var isCheck = baseService.IsCheckSms(user.name, input.code, SMSType.UpdateMobile, out error);

                if (!isCheck)
                {
                    result.msg = error;
                    return result;
                }

                result.code = 1;
                result.data = true;
                return result;

            }
            catch (Exception ex)
            {
                result.code = 2;
                result.msg = ex.Message;
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        /// <summary>
        /// 更换手机号-第二步
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("UpdateNewMobile")]
        public async Task<Response<bool>> UpdateNewMobile(UpdateNewMobileInput input)
        {
            Response<bool> result = new Response<bool>();
            result.code = 0;
            result.msg = "";
            result.data = false;
            try
            {
                var user = await db.gw_users.FindAsync(input.user_id);
                if (user == null)
                {
                    result.msg = "非法访问，你已加入黑名单，IP：" + DcRequest.GetIP();
                    return result;
                }

                var smsCode = await db.gw_base_smses.OrderByDescending(c => c.id).FirstOrDefaultAsync(c => c.user_id == input.user_id && c.status == 0 && c.type == (byte)SMSType.UpdateNewMobile);
                if (smsCode == null)
                {
                    result.msg = "验证码失效，请重新获取";
                    return result;
                }
                string error = "";
                var isCheck = baseService.IsCheckSms(smsCode.mobile, input.code, SMSType.UpdateNewMobile, out error);

                if (!isCheck)
                {
                    result.msg = error;
                    return result;
                }

                var newMobile = smsCode.mobile;

                //手机号是否已注册
                var flag = await db.gw_users.AnyAsync(u => u.name == newMobile);
                if (flag)
                {
                    result.msg = "手机号已注册";
                    return result;
                }

                //判断验证码
                var firstSMSCode = await db.gw_base_smses.OrderByDescending(c => c.id).FirstOrDefaultAsync(c => c.user_id == input.user_id && c.status == 1 && c.type == (byte)SMSType.UpdateMobile);
                if (firstSMSCode == null)
                {
                    result.msg = "权限不足";
                    return result;
                }
                if (DateTime.Now > firstSMSCode.eff_time)
                {
                    result.msg = "验证码过期,请重新认证";
                    return result;
                }
                if (input.first_code != firstSMSCode.code)
                {
                    result.msg = "请重新认证";
                    return result;
                }

                user.name = newMobile;
                db.Entry(user).Property(u => u.name).IsModified = true;

                int rows = await db.SaveChangesAsync();
                if (rows > 0)
                {
                    result.code = 1;
                    result.msg = "更换成功";
                    result.data = true;
                }
            }
            catch (Exception ex)
            {
                result.code = 2;
                result.msg = ex.Message;
                LogHelper.WriteLog(ex);
            }
            return result;
        }
        #endregion

        #region 密码
        /// <summary>
        /// 是否设置登录密码
        /// </summary>
        /// <param name="user_id">用户ID</param>
        /// <returns>
        /// data:false-未设置登录密码,ture-已设置登录密码
        /// </returns>
        [HttpGet]
        [Route("IsLoginPassword")]
        public async Task<Response<bool>> IsLoginPassword(int user_id)
        {
            Response<bool> result = new Response<bool>();
            result.code = 0;
            result.msg = "";
            result.data = false;
            try
            {
                gw_user_password paypassword = await db.gw_user_passwords.FirstOrDefaultAsync(p => p.user_id == user_id && p.type == 0);// new gw_user_pay_passwordManage().GetModelByUser(input.user_id, 0);
                result.code = 1;
                if (paypassword == null || string.IsNullOrEmpty(paypassword.password))
                {
                    result.msg = "未设置支付密码";
                    result.data = false;
                }
                else
                {
                    result.msg = "已设置支付密码";
                    result.data = true;
                }
            }
            catch (Exception ex)
            {
                result.code = 2;
                result.msg = ex.Message;
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        /// <summary>
        /// 添加登录密码
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("AddLoginPassword")]
        public async Task<Response<bool>> AddLoginPassword(AddLoginPasswordInput input)
        {
            Response<bool> result = new Response<bool>();
            result.code = 0;
            result.msg = "";
            result.data = false;
            try
            {
                var response = await IsLoginPassword(input.user_id);

                if (response.data == true)
                {
                    result.msg = response.msg;
                    return result;
                }


                if (response.code == 1 && response.data == true)
                {
                    result.msg = "已设置登录密码";
                    return result;
                }

                var user = await db.gw_users.FindAsync(input.user_id);
                if (user == null)
                {
                    result.msg = "非法访问，你已加入黑名单，IP：" + DcRequest.GetIP(); ;
                    LogHelper.WriteLog(result.msg);
                    return result;
                }

                //验证码
                string error = "";
                var isCheck = baseService.IsCheckSms(user.name, input.code, SMSType.AddLoginPassword, out error);
                if (!isCheck)
                {
                    result.msg = error;
                    return result;
                }

                gw_user_password password = new gw_user_password()
                {
                    password = EncryptionHelper.EncryptText(input.password),
                    type = 0,
                    user_id = input.user_id,
                    add_time = DateTime.Now,
                };

                db.gw_user_passwords.Add(password);

                int row = await db.SaveChangesAsync();
                result.code = 1;
                if (row > 0)
                {
                    result.msg = "添加成功";
                    result.data = true;
                }
            }
            catch (Exception ex)
            {
                result.code = 2;
                result.msg = ex.Message;
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        /// <summary>
        /// 修改登录密码
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("UpdateLoginPassword")]
        public async Task<Response<bool>> UpdateLoginPassword(UpdateLoginPasswordInput input)
        {
            Response<bool> result = new Response<bool>();
            result.code = 0;
            result.msg = "";
            result.data = false;
            try
            {
                gw_user_password payPassword = await db.gw_user_passwords.FirstOrDefaultAsync(p => p.user_id == input.user_id && p.type == 0);

                if (payPassword == null || string.IsNullOrEmpty(payPassword.password))
                {
                    result.msg = "未设置支付密码";
                    result.data = false;
                    return result;
                }
                if (payPassword.password != EncryptionHelper.EncryptText(input.password))
                {
                    result.msg = "支付密码错误";
                    result.data = false;
                    return result;
                }
                payPassword.password = EncryptionHelper.EncryptText(input.new_password);
                db.Entry(payPassword).Property(p => p.password).IsModified = true;
                var row = await db.SaveChangesAsync();
                if (row > 0)
                {
                    result.code = 1;
                    result.msg = "修改成功";
                    result.data = true;
                }
            }
            catch (Exception ex)
            {
                result.code = 2;
                result.msg = ex.Message;
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        /// <summary>
        /// 通过短信修改登录密码-找回密码
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("UpdateLoginPasswordBySMS")]
        public async Task<Response<bool>> UpdateLoginPasswordBySMS(UpdateLoginPasswordBySMSInput input)
        {
            Response<bool> result = new Response<bool>();
            result.code = 0;
            result.msg = "";
            result.data = false;
            try
            {
                if (!Validator.IsMobile(input.name))
                {
                    result.msg = "手机格式不正确";
                    return result;
                }

                gw_user user = await db.gw_users.FirstOrDefaultAsync(u => u.name == input.name);
                if (user == null)
                {
                    result.msg = "非法访问，你已加入黑名单，IP：" + DcRequest.GetIP(); ;
                    return result;
                }

                //验证码
                string error = "";
                var isCheck = baseService.IsCheckSms(user.name, input.code, SMSType.ForgetLoginPassword, out error);
                if (!isCheck)
                {
                    result.msg = error;
                    return result;
                }

                gw_user_password loginPassword = await db.gw_user_passwords.FirstOrDefaultAsync(p => p.user_id == user.id && p.type == 0);
                if (loginPassword == null)
                {
                    loginPassword = new gw_user_password()
                    {
                        type = 0,
                        user_id = user.id,
                        password = EncryptionHelper.EncryptText(input.new_password),
                        add_time = DateTime.Now,
                    };
                    db.gw_user_passwords.Add(loginPassword);
                }
                else
                {
                    loginPassword.password = EncryptionHelper.EncryptText(input.new_password);
                    db.Entry(loginPassword).Property(p => p.password).IsModified = true;
                }

                var row = await db.SaveChangesAsync();
                if (row > 0)
                {
                    result.code = 1;
                    result.msg = "修改成功";
                    result.data = true;
                }
            }
            catch (Exception ex)
            {
                result.code = 2;
                result.msg = ex.Message;
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        /// <summary>
        /// 是否设置支付密码
        /// </summary>
        /// <param name="user_id">用户ID</param>
        /// <returns>
        /// data:false-未设置支付密码,
        /// ture-已设置支付密码
        /// </returns>
        [HttpGet]
        [Route("IsPayPassword")]
        public async Task<Response<bool>> IsPayPassword(int user_id)
        {
            Response<bool> result = new Response<bool>();
            result.code = 0;
            result.msg = "";
            result.data = false;
            try
            {
                gw_user_password paypassword = await db.gw_user_passwords.FirstOrDefaultAsync(p => p.user_id == user_id && p.type == 1);// new gw_user_pay_passwordManage().GetModelByUser(input.user_id, 0);
                result.code = 1;
                if (paypassword == null || string.IsNullOrEmpty(paypassword.password))
                {
                    result.msg = "未设置支付密码";
                    result.data = false;
                }
                else
                {
                    result.msg = "已设置支付密码";
                    result.data = true;
                }
            }
            catch (Exception ex)
            {
                result.code = 2;
                result.msg = ex.Message;
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        /// <summary>
        /// 添加支付密码
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("AddPayPassword")]
        public async Task<Response<bool>> AddPayPassword(AddPayPasswordInput input)
        {
            Response<bool> result = new Response<bool>();
            result.code = 0;
            result.msg = "";
            result.data = false;
            try
            {
                var response = await IsPayPassword(input.user_id);

                if (response.data == true)
                {
                    result.msg = response.msg;
                    return result;
                }

                if (response.code == 1 && response.data == true)
                {
                    result.msg = "已设置支付密码";
                    return result;
                }

                var user = await db.gw_users.FindAsync(input.user_id);
                if (user == null)
                {
                    result.msg = "非法访问，你已加入黑名单，IP：" + DcRequest.GetIP(); ;
                    LogHelper.WriteLog(result.msg);
                    return result;
                }

                //验证码
                string error = "";
                var isCheck = baseService.IsCheckSms(user.name, input.code, SMSType.AddPayPassword, out error);
                if (!isCheck)
                {
                    result.msg = error;
                    return result;
                }

                gw_user_password password = new gw_user_password()
                {
                    password = EncryptionHelper.EncryptText(input.password),
                    type = 1,
                    user_id = input.user_id,
                    add_time = DateTime.Now,
                };

                db.gw_user_passwords.Add(password);

                int row = await db.SaveChangesAsync();
                result.code = 1;
                if (row > 0)
                {
                    result.msg = "添加成功";
                    result.data = true;
                }
            }
            catch (Exception ex)
            {
                result.code = 2;
                result.msg = ex.Message;
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        /// <summary>
        /// 修改支付密码
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("UpdatePayPassword")]
        public async Task<Response<bool>> UpdatePayPassword(UpdatePayPasswordInput input)
        {
            Response<bool> result = new Response<bool>();
            result.code = 0;
            result.msg = "";
            result.data = false;
            try
            {
                gw_user_password payPassword = await db.gw_user_passwords.FirstOrDefaultAsync(p => p.user_id == input.user_id && p.type == 1);// new gw_user_pay_passwordManage().GetModelByUser(input.user_id, 0);

                if (payPassword == null || string.IsNullOrEmpty(payPassword.password))
                {
                    result.msg = "未设置支付密码";
                    result.data = false;
                    return result;
                }
                if (payPassword.password != EncryptionHelper.EncryptText(input.password))
                {
                    result.msg = "支付密码错误";
                    result.data = false;
                    return result;
                }
                payPassword.password = EncryptionHelper.EncryptText(input.new_password);
                db.Entry(payPassword).Property(p => p.password).IsModified = true;
                var row = await db.SaveChangesAsync();
                if (row > 0)
                {
                    result.code = 1;
                    result.msg = "修改成功";
                    result.data = true;
                }
            }
            catch (Exception ex)
            {
                result.code = 2;
                result.msg = ex.Message;
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        /// <summary>
        /// 通过短信修改支付密码
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("UpdatePayPasswordBySMS")]
        public async Task<Response<bool>> UpdatePayPasswordBySMS(UpdatePasswordBySMSInput input)
        {
            Response<bool> result = new Response<bool>();
            result.code = 0;
            result.msg = "";
            result.data = false;
            try
            {
                gw_user user = await db.gw_users.FindAsync(input.user_id);
                if (user == null)
                {
                    result.msg = "非法访问，你已加入黑名单，IP：" + DcRequest.GetIP(); ;
                    return result;
                }

                //验证码
                string error = "";
                var isCheck = baseService.IsCheckSms(user.name, input.code, SMSType.ForgetPayPassword, out error);
                if (!isCheck)
                {
                    result.msg = error;
                    return result;
                }

                gw_user_password paypassword = await db.gw_user_passwords.FirstOrDefaultAsync(p => p.user_id == input.user_id && p.type == 1);

                paypassword.password = EncryptionHelper.EncryptText(input.new_password);
                db.Entry(paypassword).Property(p => p.password).IsModified = true;
                var row = await db.SaveChangesAsync();
                if (row > 0)
                {
                    result.code = 1;
                    result.msg = "修改成功";
                    result.data = true;
                }
            }
            catch (Exception ex)
            {
                result.code = 2;
                result.msg = ex.Message;
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        #endregion

        #region 我的优惠券
        /// <summary>
        /// 领取优惠券(第2批)
        /// </summary>
        /// <param name="input">地址信息输入信息</param>
        /// <returns>data:地址ID</returns>
        [HttpPost]
        [Route("AddUserCoupon")]
        public Response<string> AddUserCoupon(AddUserCouponInput input)
        {
            Response<string> result = new Response<string>();
            result.code = 0;
            result.msg = "";
            try
            {
                //用户是否已经添加了优惠券
                var flag = db.gw_user_coupons
                    .Any(c => c.user_id == input.user_id && c.coupon_id == input.coupon_id);
                if (flag)
                {
                    result.msg = "已领取";
                    return result;
                }

                //100/月 统计这个月领取了多少优惠券


                var user = db.gw_users.Find(input.user_id);

                //减少库存
                lock (AppConfig.CurrentAmount)
                {
                    var coupon = db.gw_marketing_coupons.Find(input.coupon_id);
                    if (coupon != null)
                    {
                        if (coupon.type == 2)
                        {
                            if (user.grade == (int)UserGrade.Ordinary)
                            {
                                result.msg = "您还不是趣卡会员，请开通";
                                return result;
                            }
                        }

                        if (coupon.remain_quantity - 1 < 0)
                        {
                            result.msg = "今日抢完";
                            return result;
                        }
                        coupon.remain_quantity -= 1;
                        db.Entry(coupon).Property(d => d.remain_quantity).IsModified = true;
                        int rows = db.SaveChanges();
                        if (rows > 0)
                        {
                            var log = string.Format("优惠券剩余数量:{0},减少:{1}", coupon.remain_quantity, 1);
                            LogHelper.WriteLog(log);
                        }
                    }
                }

                gw_user_coupon userCoupon = new gw_user_coupon()
                {
                    coupon_id = input.coupon_id,
                    user_id = input.user_id,
                    add_time = DateTime.Now,
                    status = (byte)CouponsStatus.Unused,
                };

                db.gw_user_coupons.Add(userCoupon);
                db.SaveChanges();

                result.code = 1;
                result.msg = "领取成功";
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                result.code = 2;
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        /// <summary>
        /// 获得用户优惠券(第2批)
        /// </summary>
        /// <param name="user_id">用户ID</param>
        /// <param name="coupons_status">优惠券状态</param>
        /// <param name="page_index">页码</param>
        /// <param name="page_size">页数</param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetUserCoupons")]
        public Response<IPagedList<GetUserCouponsOutput>> GetUserCoupons(int user_id, CouponsStatus coupons_status = CouponsStatus.Unused, int page_index = 1, int page_size = 20)
        {
            Response<IPagedList<GetUserCouponsOutput>> result = new Response<IPagedList<GetUserCouponsOutput>>();
            result.code = 0;
            result.msg = "";
            try
            {
                var source = db.gw_user_coupons
                    .Include(c => c.gw_marketing_coupon)
                    .Where(a => a.gw_marketing_coupon.deleted == false && a.gw_marketing_coupon.status == 1 && a.user_id == user_id)
                    .Select(u => new GetUserCouponsOutput()
                    {
                        coupons_status = (CouponsStatus)u.status,
                        amount = u.gw_marketing_coupon.amount,
                        coupon_id = u.coupon_id,
                        _start_date = u.gw_marketing_coupon.start_date,
                        _end_date = u.gw_marketing_coupon.end_date,
                        name = u.gw_marketing_coupon.name,
                        //picture_url = u.gw_marketing_coupon.picture_url,
                        value = u.gw_marketing_coupon.value,
                        is_all = u.gw_marketing_coupon.is_all,
                        type = u.gw_marketing_coupon.type,
                    });

                var now = DateTime.Now;

                source = source.Where(s => s.coupons_status == coupons_status);

                //过期优惠券
                if (coupons_status == CouponsStatus.Expired)
                {
                    source = source.Where(s => s._end_date < now);
                    source = source.OrderByDescending(s => s._start_date);
                }
                else
                {
                    source = source.Where(s => s._start_date <= now && s._end_date >= now);
                    source = source.OrderBy(s => s.value).ThenByDescending(s => s._start_date);
                }

                IPagedList<GetUserCouponsOutput> pagedList = new PagedList<GetUserCouponsOutput>(source, page_index, page_size);
                foreach (var item in pagedList)
                {
                    item.coupons_status = coupons_status;
                    item.start_date = TimeHelper.GetTimeStamp(item._start_date);
                    item.end_date = TimeHelper.GetTimeStamp(item._end_date);
                    item.coupon_type = (CouponType)item.type;
                }

                result.code = 1;
                result.msg = "获取成功";
                result.data = pagedList;
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                result.code = 2;
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        /// <summary>
        /// 获得商品优惠券(第2批)
        /// </summary>
        /// <param name="user_id">用户ID</param>
        /// <param name="goods_id">商品ID</param>
        /// <param name="page_index">页码</param>
        /// <param name="page_size">页数</param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetGoodsCoupons")]
        public Response<IPagedList<GetUserCouponsOutput>> GetGoodsCoupons(int user_id, int goods_id, int page_index = 1, int page_size = 20)
        {
            Response<IPagedList<GetUserCouponsOutput>> result = new Response<IPagedList<GetUserCouponsOutput>>();
            result.code = 0;
            result.msg = "";
            try
            {
                var now = DateTime.Now;
                var source = db.gw_marketing_coupons
                    .Include(c => c.gw_user_coupon)
                    .Include(c => c.gw_goods)
                    .Where(c => c.deleted == false && c.status == 1 && c.start_date <= now && c.end_date >= now && (c.gw_goods.Any(g => g.id == goods_id) || c.is_all))
                    .Select(c => new GetUserCouponsOutput()
                    {
                        user_coupon = c.gw_user_coupon.FirstOrDefault(u => u.user_id == user_id),
                        amount = c.amount,
                        coupon_id = c.id,
                        _start_date = c.start_date,
                        _end_date = c.end_date,
                        name = c.name,
                        //picture_url = c.picture_url,
                        value = c.value,
                        is_all = c.is_all,
                    });

                source = source.OrderBy(s => s.amount);

                IPagedList<GetUserCouponsOutput> pagedList = new PagedList<GetUserCouponsOutput>(source, page_index, page_size);
                foreach (var item in pagedList)
                {
                    item.start_date = TimeHelper.GetTimeStamp(item._start_date);
                    item.end_date = TimeHelper.GetTimeStamp(item._end_date);
                    if (item.user_coupon != null)
                    {
                        item.user_coupon_id = item.user_coupon.id;
                        item.coupons_status = (CouponsStatus)item.user_coupon.status;
                    }
                    else
                    {
                        item.coupons_status = CouponsStatus.Unclaimed;
                    }
                }

                result.code = 1;
                result.msg = "获取成功";
                result.data = pagedList;
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                result.code = 2;
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        #endregion

        #region 用户收藏

        /// <summary>
        /// 添加店铺收藏（第4批）
        /// </summary>
        [HttpPost]
        [Route("AddShopCollection")]
        public async Task<Response<bool>> AddShopCollection(AddShopCollectionInput input)
        {
            Response<bool> result = new Response<bool>();
            result.code = 0;
            result.msg = "";
            result.data = false;
            try
            {
                var output = await ExistShopCollection(input);
                if (output.code != 1)
                {
                    result.msg = output.msg;
                    return result;
                }

                if (output.data == true)
                {
                    result.msg = "已收藏";
                    return result;
                }

                gw_user_collection collection = new gw_user_collection()
                {
                    user_id = input.user_id,
                    add_time = DateTime.Now,
                    type = (int)CollectionType.Shop,
                    shop_id = input.shop_id,
                };

                db.gw_user_collections.Add(collection);
                int row = await db.SaveChangesAsync();
                if (row > 0)
                {
                    result.code = 1;
                    result.msg = "收藏成功";
                    result.data = true;
                }
                else
                {
                    result.code = 0;
                    result.msg = "收藏失败";
                    result.data = false;
                }
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                result.code = 2;
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        /// <summary>
        /// 取消店铺收藏（第4批）
        /// </summary>
        [HttpPost]
        [Route("RemoveShopCollection")]
        public async Task<Response<bool>> RemoveShopCollection(AddShopCollectionInput input)
        {
            Response<bool> result = new Response<bool>();
            result.code = 0;
            result.msg = "";
            result.data = false;
            try
            {
                var collection = await db.gw_user_collections.FirstOrDefaultAsync(g => g.shop_id == input.shop_id && g.user_id == input.user_id);

                if (collection == null)
                {
                    result.msg = "已取消";
                    return result;
                }
                db.gw_user_collections.Remove(collection);
                await db.SaveChangesAsync();

                result.code = 1;
                result.msg = "取消成功";
                result.data = true;
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                result.code = 2;
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        /// <summary>
        /// 是否店铺收藏(第4批)
        /// </summary>
        /// <param name="input"></param>
        /// <returns>data:ture-已收藏，false-未收藏</returns>
        [HttpPost]
        [Route("ExistShopCollection")]
        public async Task<Response<bool>> ExistShopCollection(AddShopCollectionInput input)
        {
            Response<bool> result = new Response<bool>();
            result.code = 0;
            result.msg = "";
            result.data = false;
            try
            {
                if (input.shop_id == 0)
                {
                    result.msg = "店铺不存在";
                    return result;
                }
                //记录用户查询商品名
                var collection = await db.gw_user_collections.FirstOrDefaultAsync(g => g.shop_id == input.shop_id && g.user_id == input.user_id);

                result.code = 1;
                if (collection != null)
                {
                    result.msg = "已收藏";
                    result.data = true;
                }
                else
                {
                    result.msg = "未收藏";
                    result.data = false;
                }
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                result.code = 2;
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        /// <summary>
        /// 获得收藏的店铺(第4批)
        /// </summary>
        /// <param name="user_id">用户ID</param>
        /// <param name="page_index">页码</param>
        /// <param name="page_size">页数</param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetShopCollection")]
        public Response<IPagedList<GetShopCollectionOutput>> GetShopCollection(int user_id, int page_index = 1, int page_size = 20)
        {
            Response<IPagedList<GetShopCollectionOutput>> result = new Response<IPagedList<GetShopCollectionOutput>>();
            result.code = 0;
            result.msg = "";

            try
            {
                var sources = db.gw_user_collections.Include(o => o.gw_shop).Include(o => o.gw_shop.gw_shop_property).Where(o => o.user_id == user_id && o.type == (int)CollectionType.Shop).Select(o => new GetShopCollectionOutput()
                {
                    order_count = o.gw_shop.gw_shop_property.order_count,
                    picture_url = o.gw_shop.logo,
                    shop_id = o.id,
                    shop_name = o.gw_shop.name,
                    add_time = o.add_time,
                });

                sources = sources.OrderByDescending(s => s.add_time);
                IPagedList<GetShopCollectionOutput> pageList = new PagedList<GetShopCollectionOutput>(sources, page_index, page_size);
                if (pageList != null)
                {
                    foreach (var item in pageList)
                    {
                        item.picture_url = HostHelper.GetImgUrl(item.picture_url);
                    }
                }
                result.data = pageList;
                result.code = 1;
            }
            catch (Exception ex)
            {
                result.code = 2;
                result.msg = ex.ToString();
                LogHelper.WriteLog(ex);
            }
            return result;
        }
        #endregion

        #region 所有用户
        /// <summary>
        /// 所有用户
        /// </summary>
        /// <returns></returns>
        internal List<SimpleUser> GetUsers()
        {
            var users = db.gw_users
                    .Select(u => new SimpleUser
                    {
                        id = u.id,
                        logo = u.logo,
                        name = u.name,
                        parent_id = u.parent_id,
                    })
                    .FromCache(CachePolicy.WithDurationExpiration(TimeSpan.FromSeconds(60)))
                    .ToList();
            return users;
        }
        #endregion

        #region 绑定第三方
        /// <summary>
        /// 是否绑定
        /// </summary>
        /// <param name="user_id">用户ID</param>
        /// <param name="type">绑定类型：1-QQ 2-微信</param>
        /// <returns>
        /// </returns>
        [HttpGet]
        [Route("IsBinding")]
        public async Task<Response<bool>> IsBinding(int user_id, BindingType type)
        {
            Response<bool> result = new Response<bool>();
            result.code = 0;
            result.msg = "";
            result.data = false;
            try
            {
                var flag = await db.gw_user_thirds.AnyAsync(p => p.user_id == user_id && p.type == (int)type && p.deleted == false);
                result.code = 1;
                if (flag)
                {
                    result.msg = "已绑定";
                    result.data = true;
                }
                else
                {
                    result.msg = "未绑定";
                    result.data = false;
                }
            }
            catch (Exception ex)
            {
                result.code = 2;
                result.msg = ex.Message;
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        /// <summary>
        /// 添加绑定
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("AddBinding")]
        public async Task<Response<bool>> AddBinding(AddBindingInput input)
        {
            Response<bool> result = new Response<bool>();
            result.code = 0;
            result.msg = "";
            result.data = false;
            try
            {
                var user = await db.gw_users.FindAsync(input.user_id);
                if (user == null)
                {
                    result.msg = "非法访问，你已加入黑名单，IP：" + DcRequest.GetIP(); ;
                    return result;
                }
                if (user.status == 0)
                {
                    result.msg = "黑名单用户";
                    return result;
                }
                else if (user.status == 2)
                {
                    result.msg = "用户被禁用或者被限制";
                    return result;
                }

                //是否绑定过
                var binding = await IsBinding(input.user_id, input.third_login.type);
                if (binding.data)
                {
                    result.msg = "已绑定";
                    return result;
                }

                //判断第三方是否绑定
                var isBinding = await db.gw_user_thirds.AnyAsync(t => t.open_id == input.third_login.open_id);
                if (isBinding)
                {
                    result.msg = "已绑定";
                    return result;
                }


                //验证
                if (input.third_login.type == BindingType.WeChat)
                {
                    string url = string.Format("https://api.weixin.qq.com/sns/auth?access_token={0}&openid={1}", input.third_login.access_token, input.third_login.open_id);
                    using (var client = new HttpClient())
                    {
                        // 创建一个异步GET请求，当请求返回时继续处理（Continue-With模式）
                        HttpResponseMessage response = await client.GetAsync(url);
                        string resultStr = await response.Content.ReadAsStringAsync();

                        if (!resultStr.Contains("\"errmsg\":\"ok\""))
                        {
                            result.msg = "非法访问";
                            return result;
                        }
                    }
                }
                else
                {
                    string url = string.Format("https://graph.qq.com/oauth2.0/me?access_token={0}", input.third_login.access_token);
                    using (var client = new HttpClient())
                    {
                        // 创建一个异步GET请求，当请求返回时继续处理（Continue-With模式）
                        HttpResponseMessage response = await client.GetAsync(url);
                        string resultStr = await response.Content.ReadAsStringAsync();

                        if (!resultStr.Contains(input.third_login.open_id))
                        {
                            result.msg = "非法访问";
                            return result;
                        }
                    }
                }

                //绑定
                var oauth = new gw_user_third()
                {
                    access_token = input.third_login.access_token,
                    add_time = DateTime.Now,
                    deleted = false,
                    gender = input.third_login.gender,
                    icon_url = input.third_login.icon_url,
                    name = input.third_login.name,
                    oauth_consumer_key = input.third_login.oauth_consumer_key,
                    open_id = input.third_login.open_id,
                    status = 1,
                    type = (byte)input.third_login.type,
                    uid = input.third_login.uid,
                    union_id = input.third_login.union_id,
                    user_id = user.id,
                    usid = input.third_login.usid,
                };
                db.gw_user_thirds.Add(oauth);
                await db.SaveChangesAsync();

                result.code = 1;
                result.msg = "绑定成功";
                result.data = true;
            }
            catch (Exception ex)
            {
                result.code = 2;
                result.msg = ex.Message;
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        /// <summary>
        /// 解除绑定
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("DeleteBinding")]
        public async Task<Response<bool>> DeleteBinding(DeleteBindingInput input)
        {
            Response<bool> result = new Response<bool>();
            result.code = 0;
            result.msg = "";
            result.data = false;
            try
            {
                //是否绑定过
                var binding = await db.gw_user_thirds
                    .FirstOrDefaultAsync(p => p.user_id == input.user_id && p.type == (int)input.type);

                result.code = 1;
                if (binding == null)
                {
                    result.msg = "已解除";
                    return result;
                }

                db.gw_user_thirds.Remove(binding);
                await db.SaveChangesAsync();

                result.code = 1;
                result.msg = "解除成功";
                result.data = true;
            }
            catch (Exception ex)
            {
                result.code = 2;
                result.msg = ex.Message;
                LogHelper.WriteLog(ex);
            }
            return result;
        }
        #endregion

        #region 会员

        /// <summary>
        /// 获得VIP规则列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("GetVipRules")]
        [CacheOutput(ClientTimeSpan = CACHETIME, ServerTimeSpan = CACHETIME)]
        public async Task<Response<GetVipRulesOutput>> GetVipRules()
        {
            Response<GetVipRulesOutput> result = new Response<GetVipRulesOutput>();
            result.code = 0;
            result.msg = "";

            try
            {
                var sources = await db.gw_user_rules
                    .Include(r => r.gw_user_rule_picture)
                    .OrderBy(s => s.sort)
                    .Where(s => s.status == 1)
                    .Select(s => new GetVipRuleOutput()
                    {
                        user_rule_id = s.id,
                        title = s.title,
                        title_sub = s.title_sub,
                        sort = s.sort,
                        subhead = s.subhead,
                        content = s.content,
                        picture_url = s.picture_url,
                        summary = s.summary,
                        ico = s.ico,
                        selected_ico = s.selected_ico,
                        pictures = s.gw_user_rule_picture.OrderBy(p => p.sort).Select(p => p.url).ToList(),
                    }).ToListAsync();
                GetVipRulesOutput output = new GetVipRulesOutput();
                if (sources != null && sources.Count > 0)
                {
                    foreach (var item in sources)
                    {
                        item.picture_url = HostHelper.GetImgUrl(item.picture_url);
                        item.ico = HostHelper.GetImgUrl(item.ico);
                        item.selected_ico = HostHelper.GetImgUrl(item.selected_ico);
                        item.pictures = HostHelper.GetImgUrl(item.pictures);
                    }
                }

                output.rules = sources;

                DateTime dtEnd = DateTime.Parse("2018-10-11");
                output.is_show = true;
                if (DateTime.Now > dtEnd)
                {
                    output.is_show = false;
                }

                var res = new GoodsController().GetMemberGoods(0, "", 0, Sort.DateDes, 1, 10);
                if (res.code == 1)
                {
                    output.member_goods = res.data;
                }

                var member_price = await db.gw_settings.Where(s => s.name.Contains("member_")).ToListAsync();
                if (member_price != null)
                {
                    output.member_price = member_price.FirstOrDefault(s => s.name == "member_price").value;
                    output.member_promote_price = member_price.FirstOrDefault(s => s.name == "member_promote_price").value;
                }

                result.data = output;
                result.code = 1;
            }
            catch (Exception ex)
            {
                result.code = 2;
                result.msg = ex.ToString();
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        /// <summary>
        /// 根据规则ID获得VIP规则
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("GetVipRule")]
        private async Task<Response<GetVipRuleOutput>> GetVipRule(int user_rule_id)
        {
            Response<GetVipRuleOutput> result = new Response<GetVipRuleOutput>();
            result.code = 0;
            result.msg = "";

            try
            {
                var sources = await db.gw_user_rules
                    .OrderBy(s => s.sort)
                    .Where(s => s.status == 1)
                    .Select(s => new GetVipRuleOutput()
                    {
                        user_rule_id = s.id,
                        title = s.title,
                        sort = s.sort,
                        content = s.content,
                        picture_url = s.picture_url,
                        summary = s.summary,
                        ico = s.ico,
                        selected_ico = s.selected_ico,
                    }).FirstOrDefaultAsync(u => u.user_rule_id == user_rule_id);

                result.data = sources;
                result.code = 1;
            }
            catch (Exception ex)
            {
                result.code = 2;
                result.msg = ex.ToString();
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        #endregion

    }
}